<script setup lang="ts">
import { reqGetRuleList } from '@/api/rule'
import { showMessage } from '@/utils/elementTools'
import { reqRoleList, reqDeleteRole, reqAddRole, reqUpdateRole, reqUpdateRoleStatus, reqConfigRole } from '@/api/role'
import { useInitTable, useInitForm } from '@/composables/useCommon'

const { tableData, loading, getData, handleDelete, handleStatusChange } = useInitTable({
  getList: reqRoleList,
  delete: reqDeleteRole,
  updateStatus: reqUpdateRoleStatus
  // onGetListSuccess: (res: any) => {
  //   roles.value = res.data.roles
  //   tableData.value = res.data.list
  //   defaultExpandedKeys.value = res.data.list.map((item: any) => item.id)
  // },
})

const { formDrawerRef, formRef, drawerTitle, form, rules, handleSubmit, handleAdd, handleEdit } = useInitForm({
  getData,
  initialForm: { name: '', desc: '', status: 1 },
  rules: {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }]
  },
  update: reqUpdateRole,
  create: reqAddRole
})

const formSetRuleDrawerRef = ref(false)
const rulesList = ref([])
const roleId = ref(0)
const ruleIds = ref<number[]>([]) // 记录当前角色的所有规则id
const treeHeight = ref(300)
const elTreeRef = ref(null)
const defaultExpandedKeys = ref([]) // 默认 展开的节点， 需要有node-key

const openSetRule = (row: any) => {
  roleId.value = row.id
  ruleIds.value = row.rules.map((item: any) => item.id)
  treeHeight.value = window.innerHeight - 170

  reqGetRuleList().then((res) => {
    rulesList.value = res.data.list
    defaultExpandedKeys.value = res.data.list.map((item: any) => item.id)
  })
  formSetRuleDrawerRef.value.showDrawer()
  setTimeout(() => {
    elTreeRef.value!.setCheckedKeys(ruleIds.value)
  }, 150)
}
// 这里定义了一个名为 `handleTreeCheck` 的函数，它使用了剩余参数语法 `...e`，这意味着它可以接受任意数量的参数，并将这些参数收集到一个数组 `e` 中。
// 参数类型指定为 `any`，表示可以接受任何类型的参数。这个函数通常用于处理 `el-tree` 组件的 `check` 事件，当树节点的复选框状态发生变化时会触发该事件。
// 一般来说，`el-tree` 的 `check` 事件会传递两个参数：当前被操作的节点数据和一个包含选中节点信息的对象，如 `checkedKeys`（选中的节点键数组）和 `halfCheckedKeys`（半选中的节点键数组）。
const handleTreeCheck = (...e: any) => {
  const { checkedKeys, halfCheckedKeys } = e[1]
  // check-strictly 不用来回设置 ,只要halfCheckedKeys 父节点 不加入就行
  ruleIds.value = [...checkedKeys]
}
const handleSetRuleSubmit = () => {
  formSetRuleDrawerRef.value.showLoading()
  reqConfigRole(roleId.value, ruleIds.value)
    .then((res) => {
      formSetRuleDrawerRef.value.hideDrawer()
      showMessage('配置成功')
      getData()
    })
    .finally(() => {
      formSetRuleDrawerRef.value.hideLoading()
    })
}
</script>

<template>
  <div>
    <el-card shadow="never" style="border: 0; margin: 10px">
      <ListHeader @refresh="getData" @create="handleAdd" />
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="desc" label="描述" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row, scope.row.status)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button type="success" text size="small" icon="eleme" @click="openSetRule(scope.row)">配置权限</el-button>
            <el-button type="primary" text size="small" icon="edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-popconfirm title="是否确认要删除吗?" width @confirm="handleDelete(scope.row.id)">
              <template #reference>
                <el-button size="small" text type="danger" icon="delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" style="width: 30%"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="form.desc" type="textarea" :row="5" placeholder="请输入描述" style="width: 70%"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
    </FormDrawer>

    <FormDrawer ref="formSetRuleDrawerRef" title="配置权限" @submit="handleSetRuleSubmit">
      <!-- el-tree-v2 默认展开不生效 -->
      <el-tree
        ref="elTreeRef"
        node-key="id"
        :default-expanded-keys="defaultExpandedKeys"
        :data="rulesList"
        :props="{ label: 'name', children: 'child' }"
        show-checkbox
        :height="treeHeight"
        @check="handleTreeCheck"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <el-tag size="small" :type="data.menu ? 'primary' : 'info'">
              {{ data.menu ? '菜单' : '权限' }}
            </el-tag>
            <el-icon v-if="data.icon" :size="16" style="margin: 0 8px">
              <component :is="data.icon" />
            </el-icon>
            <span>{{ node.label }}</span>
          </div>
        </template>
      </el-tree>
    </FormDrawer>
  </div>
</template>

<style lang="scss" scoped>
.custom-tree-node {
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 20px;
}
:deep(.el-tree-node__content) {
  padding: 20px;
}
</style>
